<?php
namespace App\DBs;

use Illuminate\Support\Facades\DB;

class CommentDB extends BaseDB
{
    /**
     * 评论
     */

    public $tPl = 'v_pl';
    public $tTxt = 'v_pl_txt';

    public function __construct()
    {
    }

    /**
     * 列表
     */
    public function getIndex($wx,$vid)
    {
        $query = DB::table($this->tTxt)->where('del',0)->where('wx',$wx)->where('vid',$vid);
        $total = $query->count();
        $models = $query->skip(0)->take(10)->orderBy('id','desc')->get();
        if (!count($models)) {
            return array('code'=>'-1','msg'=>'没有数据');
        }
        $models = $this->jsonToArr($models);
        $items = array();
        foreach ($models as $model) {
            $createTime = $model['created_at'] ? date('Y.m.d',$model['created_at']) : '-';
            $items[] = [
                'id'=>$model['id'], 'vid'=>$model['vid'], 'wx'=>$model['wx'],
                'detail'=>$model['detail'], 'createTime'=>$createTime,
            ];
        }
        return array('code'=>'0','msg'=>'success','data'=>$items,'total'=>$total);
    }

    /**
     * 新增
     */
    public function setAdd($wx,$vid,$txt)
    {
        $resOnes = DB::table($this->tPl)->where('del',0)
            ->where('wx',$wx)->where('vid',$vid)->get();
        $resOne = count($resOnes) ? $this->jsonToArr($resOnes[0]) : '';
        $pl = $resOne ? $resOne['id'] : 0;
        //开启事务
        DB::beginTransaction();
        try {
            if (!$pl) {
                $lastId = DB::table($this->tPl)->insertGetId([
                    'wx'=>$wx,'vid'=>$vid,'created_at'=>time(),
                ]);
                if (!$lastId) { return array('code'=>'-2','msg'=>'评论失败'); }
            } else {
                $lastId = $pl;
            }
            $resDb = DB::table($this->tTxt)->insertGetId([
                'wx'=>$wx,'vid'=>$vid,'pl'=>$lastId,'detail'=>$txt,'created_at'=>time(),
            ]);
            if (!$resDb) { return array('code'=>'-2','msg'=>'评论失败'); }
            //提交事务
            DB::commit();
            return array('code'=>'0', 'msg'=>'操作成功');
        } catch (\Exception $e) {
            //事务回滚
            DB::rollBack();
            return array('code'=>'-1', 'msg'=>'操作失败：'.$e);
        }
    }
}